package com.hm.health.Fragment;

import android.os.Bundle;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.goodix.fragment.BaseFragment;
import com.goodix.comsdk.entity.MeasureResult;
import com.goodix.comsdk.sdk.OnHBDDataListener;
import com.goodix.libromablecom.sdk.cardiff.arguments.StartArgumentsKeyEnum;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.View.RecyclerViewDivider;
import com.hm.health.adapter.MeasureResultAdapter;
import com.hm.health.entity.BleDevicesInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenshi on 2019/12/23.
 */

public class MeasureResultFragment extends BaseFragment{

    public static final String ARGS_FUNCTION_NAME = "ARGS_FUNCTION_NAME";
    private static final String ARGS_DEVICE_LSIT = "args_device_list";

    private List<String> mBleDevices = new ArrayList<>();
    private List<MeasureResult> mNormalMeasureResultBuffer = new ArrayList<>();
    private List<MeasureResult> mNormalMeasureResult = new ArrayList<>();
    private MeasureResultAdapter mNormalMeasureResultAdapter;

    private RecyclerView mRvNormalMeasureResult;
    private GridLayoutManager mGridLayoutManagerNormal;
    private int mSpanCnt = 1;
    private String mFunctionName;

    private List<MeasureResult> mGlobalMeasureResult = new ArrayList<>();
    private MeasureResultAdapter mGlobalMeasureResultAdapter;
    private RecyclerView mRvGlobalMeasureResult;
    private GridLayoutManager mGridLayoutManagerGlobal;
    private ScheduledExecutorService mExecutorService;

    @Override
    public int getCreateViewLayoutResId() {
        return R.layout.fragment_measure_result;
    }

    @Override
    public void initData() {
        mFunctionName = getArguments().getString(ARGS_FUNCTION_NAME,"");
        String jsonStr = getArguments().getString(MeasureResultFragment.ARGS_DEVICE_LSIT, "");
        if (!jsonStr.isEmpty()) {
            List<BleDevicesInfo> devicesInfos = new Gson().fromJson(jsonStr,
                    new TypeToken<List<BleDevicesInfo>>() {
                    }.getType());
            if (null != devicesInfos) {
                for (BleDevicesInfo devicesInfo : devicesInfos) {
                    mBleDevices.add(devicesInfo.getDeviceAddress());
                }
            }
        }
    }

    @Override
    public void findView(View inflateView, Bundle savedInstanceState) {
        mRvNormalMeasureResult = findViewById(R.id.rv_measure_results);
        mRvGlobalMeasureResult = findViewById(R.id.rv_measure_results1);
    }

    @Override
    public void initView(View inflateView, Bundle savedInstanceState) {
        mGridLayoutManagerNormal = new GridLayoutManager(getContext(), 12);
        mRvNormalMeasureResult.setLayoutManager(mGridLayoutManagerNormal);
        mRvNormalMeasureResult.setItemAnimator(new DefaultItemAnimator());
        mRvNormalMeasureResult.setHasFixedSize(true);
        mRvNormalMeasureResult.addItemDecoration(new RecyclerViewDivider(getContext(), GridLayoutManager.VERTICAL));
        mRvNormalMeasureResult.addItemDecoration(new RecyclerViewDivider(getContext(), GridLayoutManager.HORIZONTAL));
        mNormalMeasureResultAdapter = new MeasureResultAdapter(getContext(),
                mNormalMeasureResult, R.layout.item_measure_result);
        mRvNormalMeasureResult.setAdapter(mNormalMeasureResultAdapter);

        mGridLayoutManagerGlobal = new GridLayoutManager(getContext(), 2);
        mRvGlobalMeasureResult.setLayoutManager(mGridLayoutManagerGlobal);
        mRvGlobalMeasureResult.setItemAnimator(new DefaultItemAnimator());
        mRvGlobalMeasureResult.setHasFixedSize(true);
        mRvGlobalMeasureResult.addItemDecoration(new RecyclerViewDivider(getContext(), GridLayoutManager.VERTICAL));
        mRvGlobalMeasureResult.addItemDecoration(new RecyclerViewDivider(getContext(), GridLayoutManager.HORIZONTAL));
        mGlobalMeasureResultAdapter = new MeasureResultAdapter(getContext(), mGlobalMeasureResult, R.layout.item_measure_result1);
        mRvGlobalMeasureResult.setAdapter(mGlobalMeasureResultAdapter);

        mExecutorService = Executors.newSingleThreadScheduledExecutor();
        mExecutorService.scheduleAtFixedRate(() -> getActivity().runOnUiThread(() -> {
            updateNoramlMeasureResult();
            changedShowItemColumnCnt();
            mNormalMeasureResultAdapter.notifyDataSetChanged();
            mGlobalMeasureResultAdapter.notifyDataSetChanged();
        }), 0, 1000, TimeUnit.MILLISECONDS);
    }

    private void updateNoramlMeasureResult() {
        // sort display order
        mNormalMeasureResult.clear();
        for (String addr : mBleDevices) {
            for (MeasureResult r : mNormalMeasureResultBuffer) {
                if (r.getDeviceAddress().equalsIgnoreCase(addr)) {
                    mNormalMeasureResult.add(r);
                }
            }
        }
    }

    private OnHBDDataListener mOnHBDDataListener = new OnHBDDataListener() {
        @Override
        public void onDataChanged(String dataType, int[] dataArr) {

        }

        @Override
        public void onMeasureResult(MeasureResult result) {
            updateGlobalMeasureResult(result);
            updateNormalMeasureResultBuffer(result);
        }
    };

    private void updateNormalMeasureResultBuffer(MeasureResult result) {
        if ((result.mFunctionName!= null) && (result.mFunctionName.compareTo(mFunctionName) != 0)) {
            return;
        }

        int pos = mNormalMeasureResultBuffer.indexOf(result);
        if ((pos >= 0) && (pos < mNormalMeasureResultBuffer.size())) {
            mNormalMeasureResultBuffer.set(pos, result);
        } else {
            mNormalMeasureResultBuffer.add(result);
        }
    }

    private void updateGlobalMeasureResult(MeasureResult result) {
        if (StartArgumentsKeyEnum.AppFunction_GLOBAL.compareToIgnoreCase(result.mFunctionName.toUpperCase()) != 0) {
            return;
        }

        int pos = mGlobalMeasureResult.indexOf(result);
        if ((pos >= 0) && (pos < mGlobalMeasureResult.size())) {
            mGlobalMeasureResult.set(pos, result);
        } else {
            mGlobalMeasureResult.add(result);
        }
    }

    private void changedShowItemColumnCnt() {
        int cnt = mNormalMeasureResult.size();

       if (cnt > 0 && cnt <= 4) {
            cnt = 12 / cnt;
        } else {
            cnt = 4;
        }

        if (cnt == mSpanCnt) {
            return;
        }

        mSpanCnt = cnt;
        mGridLayoutManagerNormal.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return mSpanCnt;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MyApplication.getHBDTestClient().registerHBDDataListener(mOnHBDDataListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        MyApplication.getHBDTestClient().unRegisterHBDDataListener(mOnHBDDataListener);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mExecutorService) {
            mExecutorService.shutdownNow();
        }
    }

    public static Fragment newInstance(String functionName, List<BleDevicesInfo> devicesInfos) {
        MeasureResultFragment fragment = new MeasureResultFragment();
        Bundle args = new Bundle();
        args.putString(MeasureResultFragment.ARGS_FUNCTION_NAME, functionName);
        args.putString(MeasureResultFragment.ARGS_DEVICE_LSIT, new Gson().toJson(devicesInfos));
        fragment.setArguments(args);
        return fragment;
    }
}
